<template>
  <div class="property-detail">
    <div class="container">
      <!-- 房源图片轮播 -->
      <div class="image-gallery">
        <el-carousel height="500px" indicator-position="outside">
          <el-carousel-item v-for="(image, index) in property.images" :key="index">
            <div class="gallery-item" :style="{ backgroundImage: `url(${image})` }">
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>

      <div class="detail-content">
        <div class="main-content">
          <!-- 房源基本信息 -->
          <div class="property-header">
            <div class="property-title">
              <h1>{{ property.title }}</h1>
              <div class="property-badges">
                <el-tag v-if="property.isHot" type="danger">热门</el-tag>
                <el-tag v-if="property.isVerified" type="success">认证</el-tag>
                <el-tag v-if="property.isInstant" type="warning">即时确认</el-tag>
              </div>
            </div>
            <div class="property-actions">
              <el-button @click="toggleFavorite" :type="property.isFavorite ? 'primary' : ''">
                <el-icon><Star /></el-icon>
                {{ property.isFavorite ? '已收藏' : '收藏' }}
              </el-button>
              <el-button @click="shareProperty">
                <el-icon><Share /></el-icon>
                分享
              </el-button>
            </div>
          </div>

          <!-- 房源位置和评分 -->
          <div class="property-meta">
            <div class="location">
              <el-icon><Location /></el-icon>
              <span>{{ property.location }}</span>
            </div>
            <div class="rating">
              <el-rate v-model="property.rating" disabled show-score />
              <span class="review-count">({{ property.reviewCount }}条评价)</span>
            </div>
          </div>

          <!-- 房源描述 -->
          <div class="property-description">
            <h3>房源介绍</h3>
            <p>{{ property.description }}</p>
          </div>

          <!-- 房源设施 -->
          <div class="property-amenities">
            <h3>设施服务</h3>
            <div class="amenities-grid">
              <div v-for="amenity in property.amenities" :key="amenity.name" class="amenity-item">
                <el-icon><component :is="amenity.icon" /></el-icon>
                <span>{{ amenity.name }}</span>
              </div>
            </div>
          </div>

          <!-- 房源规则 -->
          <div class="property-rules">
            <h3>入住规则</h3>
            <div class="rules-grid">
              <div class="rule-item">
                <h4>入住时间</h4>
                <p>{{ property.rules.checkIn }}</p>
              </div>
              <div class="rule-item">
                <h4>退房时间</h4>
                <p>{{ property.rules.checkOut }}</p>
              </div>
              <div class="rule-item">
                <h4>取消政策</h4>
                <p>{{ property.rules.cancellation }}</p>
              </div>
              <div class="rule-item">
                <h4>入住人数</h4>
                <p>最多{{ property.rules.maxGuests }}人</p>
              </div>
            </div>
          </div>

          <!-- 用户评价 -->
          <div class="property-reviews">
            <h3>用户评价 ({{ propertyReviews.length }})</h3>
            <div class="reviews-summary">
              <div class="rating-breakdown">
                <div class="rating-item">
                  <span>清洁度</span>
                  <el-progress :percentage="property.ratingBreakdown.cleanliness" :show-text="false" />
                  <span>{{ property.ratingBreakdown.cleanliness }}%</span>
                </div>
                <div class="rating-item">
                  <span>位置</span>
                  <el-progress :percentage="property.ratingBreakdown.location" :show-text="false" />
                  <span>{{ property.ratingBreakdown.location }}%</span>
                </div>
                <div class="rating-item">
                  <span>服务</span>
                  <el-progress :percentage="property.ratingBreakdown.service" :show-text="false" />
                  <span>{{ property.ratingBreakdown.service }}%</span>
                </div>
                <div class="rating-item">
                  <span>性价比</span>
                  <el-progress :percentage="property.ratingBreakdown.value" :show-text="false" />
                  <span>{{ property.ratingBreakdown.value }}%</span>
                </div>
              </div>
            </div>
            
            <div class="reviews-list">
              <div v-if="propertyReviews.length > 0">
                <div v-for="review in propertyReviews" :key="review.id" class="review-item">
                  <div class="review-header">
                    <div class="reviewer-info">
                      <el-avatar :src="review.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
                      <div class="reviewer-details">
                        <h4>{{ review.userName }}</h4>
                        <p>{{ formatDate(review.createdAt) }}</p>
                      </div>
                    </div>
                    <div class="review-rating">
                      <el-rate v-model="review.rating" disabled />
                    </div>
                  </div>
                  <div class="review-content">
                    <p>{{ review.content }}</p>
                    <div class="review-ratings" v-if="review.cleanlinessRating || review.checkInRating || review.valueRating">
                      <div class="rating-tag" v-if="review.cleanlinessRating">
                        清洁度: <el-rate v-model="review.cleanlinessRating" disabled size="small" />
                      </div>
                      <div class="rating-tag" v-if="review.checkInRating">
                        入住体验: <el-rate v-model="review.checkInRating" disabled size="small" />
                      </div>
                      <div class="rating-tag" v-if="review.valueRating">
                        性价比: <el-rate v-model="review.valueRating" disabled size="small" />
                      </div>
                    </div>
                    
                    <!-- 商家回复 -->
                    <div v-if="review.replyContent" class="host-reply">
                      <div class="reply-header">
                        <el-icon class="reply-icon"><ChatDotRound /></el-icon>
                        <span class="reply-label">房东回复</span>
                        <span class="reply-date" v-if="review.replyAt">· {{ formatDate(review.replyAt) }}</span>
                      </div>
                      <div class="reply-content">
                        {{ review.replyContent }}
                      </div>
                    </div>
                  </div>
                  <div class="review-actions">
                    <el-button 
                      text
                      @click="likeReview(review.id)"
                      :class="{ 'is-liked': review.isLiked }"
                    >
                      <span class="like-icon" :class="{ 'active': review.isLiked }">👍</span>
                      <span>{{ review.likes || 0 }}</span>
                    </el-button>
                  </div>
                </div>
              </div>
              <div v-else class="no-reviews">
                <el-empty description="还没有评价，快来成为第一个评价的人吧！" />
              </div>
            </div>
          </div>
        </div>

        <!-- 预订侧边栏 -->
        <div class="booking-sidebar">
          <div class="booking-card">
            <div class="price-section">
              <div class="price">
                <span class="amount">¥{{ property.price }}</span>
                <span class="unit">/晚</span>
              </div>
              <div class="price-details">
                <div class="price-item">
                  <span>¥{{ property.price }} × 2晚</span>
                  <span>¥{{ property.price * 2 }}</span>
                </div>
                <div class="price-item">
                  <span>服务费</span>
                  <span>¥{{ Math.round(property.price * 0.1) }}</span>
                </div>
                <div class="price-item total">
                  <span>总计</span>
                  <span>¥{{ Math.round(property.price * 2.1) }}</span>
                </div>
              </div>
            </div>

            <div class="booking-form">
              <el-form :model="bookingForm" label-width="80px">
                <el-form-item label="入住日期">
                  <el-date-picker
                    v-model="bookingForm.checkIn"
                    type="date"
                    placeholder="选择入住日期"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="退房日期">
                  <el-date-picker
                    v-model="bookingForm.checkOut"
                    type="date"
                    placeholder="选择退房日期"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="入住人数">
                  <el-select v-model="bookingForm.guests" placeholder="选择人数" style="width: 100%">
                    <el-option label="1人" value="1" />
                    <el-option label="2人" value="2" />
                    <el-option label="3人" value="3" />
                    <el-option label="4人" value="4" />
                    <el-option label="5人以上" value="5+" />
                  </el-select>
                </el-form-item>
              </el-form>

              <el-button type="primary" size="large" @click="handleBooking" class="booking-btn">
                立即预订
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../../stores/user'
import request from '../../api/request'
import { addFavorite, cancelFavorite, getFavorites } from '../../api/favorites'
import { toggleReviewLike, getLikesCount, checkIsLiked } from '../../api/reviews'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 房源评论数据
const propertyReviews = ref([])

// 房源数据
const property = ref({
  id: 1,
  title: '温馨小院民宿',
  location: '北京·朝阳区·三里屯',
  price: 299,
  rating: 4.8,
  reviewCount: 128,
  isHot: true,
  isVerified: true,
  isInstant: true,
  isFavorite: false,
  images: [
    'https://images.unsplash.com/photo-1566073771259-6a8506099945?w=800&h=500&fit=crop',
    'https://images.unsplash.com/photo-1571896349842-33c89424de2d?w=800&h=500&fit=crop',
    'https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?w=800&h=500&fit=crop',
    'https://images.unsplash.com/photo-1522708323590-d24dbb6b0267?w=800&h=500&fit=crop'
  ],
  description: '位于朝阳区三里屯的温馨小院民宿，环境优雅，设施齐全。房源采用现代简约风格装修，配备齐全的生活设施，为您提供舒适的住宿体验。周边交通便利，步行即可到达地铁站，距离三里屯商圈仅需5分钟车程。',
  amenities: [
    { name: 'WiFi', icon: 'Wifi' },
    { name: '空调', icon: 'WindPower' },
    { name: '厨房', icon: 'Kitchen' },
    { name: '洗衣机', icon: 'Refresh' },
    { name: '停车位', icon: 'Car' },
    { name: '电视', icon: 'VideoPlay' },
    { name: '冰箱', icon: 'Refrigerator' },
    { name: '热水器', icon: 'Sunny' }
  ],
  rules: {
    checkIn: '14:00后',
    checkOut: '12:00前',
    cancellation: '入住前24小时可免费取消',
    maxGuests: 4
  },
  ratingBreakdown: {
    cleanliness: 95,
    location: 88,
    service: 92,
    value: 90
  },
  reviews: [
    {
      id: 1,
      name: '张先生',
      avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=50&h=50&fit=crop&crop=face',
      date: '2024-01-15',
      rating: 5,
      content: '非常棒的住宿体验！房间干净整洁，设施齐全，房东也很热情。位置很好，交通便利，强烈推荐！',
      likes: 12
    },
    {
      id: 2,
      name: '李女士',
      avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?w=50&h=50&fit=crop&crop=face',
      date: '2024-01-10',
      rating: 4,
      content: '整体不错，房间很温馨，就是隔音稍微差一点，其他都很好。',
      likes: 8
    },
    {
      id: 3,
      name: '王先生',
      avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=50&h=50&fit=crop&crop=face',
      date: '2024-01-08',
      rating: 5,
      content: '性价比很高，房间装修很有特色，房东服务态度很好，下次还会选择这里。',
      likes: 15
    }
  ]
})

// 预订表单
const bookingForm = reactive({
  checkIn: '',
  checkOut: '',
  guests: ''
})

// 初始化
onMounted(() => {
  // 根据路由参数加载房源详情
  const propertyId = route.params.id || property.value.id
  console.log('加载房源详情:', propertyId)
  
  // 加载该房源的评论
  loadPropertyReviews(propertyId)
  
  // 检查是否已收藏
  checkFavoriteStatus(propertyId)
})

// 加载房源评论
const loadPropertyReviews = async (propertyId) => {
  try {
    const response = await request.get(`/api/reviews/findByPropertyId?propertyId=${propertyId}`)
    console.log('获取房源评论数据:', response)
    
    // 处理响应数据
    let reviews = []
    if (Array.isArray(response)) {
      reviews = response
    } else if (Array.isArray(response.data)) {
      reviews = response.data
    } else if (response.code === 200 && Array.isArray(response.data)) {
      reviews = response.data
    } else {
      console.error('返回数据格式不正确:', response)
      reviews = []
    }
    
    // 获取当前用户ID
    const currentUserId = userStore.userInfo?.id
    
    // 为每条评论添加点赞数和点赞状态
    propertyReviews.value = await Promise.all(reviews.map(async (review) => {
      try {
        // 获取点赞数
        const likesCount = await getLikesCount(review.id)
        
        // 检查当前用户是否已点赞
        let isLiked = false
        if (currentUserId) {
          const likedStatus = await checkIsLiked({
            reviewId: review.id,
            userId: currentUserId
          })
          isLiked = likedStatus > 0
        }
        
        return {
          ...review,
          likes: likesCount || 0,
          isLiked: isLiked
        }
      } catch (error) {
        console.error(`获取评论${review.id}的点赞数失败:`, error)
        return {
          ...review,
          likes: 0,
          isLiked: false
        }
      }
    }))
    
    // 更新评价数量
    property.value.reviewCount = propertyReviews.value.length
    
    // 计算平均评分
    if (propertyReviews.value.length > 0) {
      const avgRating = propertyReviews.value.reduce((sum, r) => sum + (r.rating || 0), 0) / propertyReviews.value.length
      property.value.rating = Math.round(avgRating * 10) / 10
    }
    
    console.log('最终设置的评论数据:', propertyReviews.value)
  } catch (error) {
    console.error('加载评论失败:', error)
    ElMessage.error('加载评论失败')
    propertyReviews.value = []
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 检查收藏状态
const checkFavoriteStatus = async (propertyId) => {
  try {
    const response = await getFavorites()
    const favorites = Array.isArray(response) ? response : (response.data || [])
    property.value.isFavorite = favorites.some(f => f.propertyId === parseInt(propertyId))
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换收藏状态
const toggleFavorite = async () => {
  const propertyId = route.params.id || property.value.id
  
  try {
    if (property.value.isFavorite) {
      // 取消收藏
      await cancelFavorite(propertyId)
      property.value.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      // 添加收藏
      await addFavorite(propertyId)
      property.value.isFavorite = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 分享房源
const shareProperty = () => {
  // 实现分享功能
  console.log('分享房源')
}

// 点赞/取消点赞评论（统一处理）
const likeReview = async (reviewId) => {
  try {
    // 检查用户是否登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    const userId = userStore.userInfo?.id
    if (!userId) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    const review = propertyReviews.value.find(r => r.id === reviewId)
    if (!review) {
      ElMessage.error('评论不存在')
      return
    }

    // 调用统一的点赞切换接口
    const result = await toggleReviewLike({
      reviewId: reviewId,
      userId: userId
    })
    
    // 根据返回结果更新UI
    if (result === 1) {
      // 点赞成功
      review.isLiked = true
      review.likes += 1
      ElMessage.success('点赞成功')
    } else if (result === 0) {
      // 取消点赞成功
      review.isLiked = false
      review.likes = Math.max(0, review.likes - 1)
      ElMessage.success('已取消点赞')
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 回复评价
const replyReview = (reviewId) => {
  console.log('回复评价:', reviewId)
}

// 处理预订
const handleBooking = () => {
  if (!bookingForm.checkIn || !bookingForm.checkOut || !bookingForm.guests) {
    ElMessage.warning('请填写完整的预订信息')
    return
  }
  
  router.push({
    path: `/booking/${property.value.id}`,
    query: {
      checkIn: bookingForm.checkIn,
      checkOut: bookingForm.checkOut,
      guests: bookingForm.guests
    }
  })
}
</script>

<style scoped>
.property-detail {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.image-gallery {
  margin-bottom: 30px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gallery-item {
  height: 500px;
  background-size: cover;
  background-position: center;
}

.detail-content {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
}

.main-content {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.property-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.property-title h1 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 10px;
}

.property-badges {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.property-actions {
  display: flex;
  gap: 10px;
}

.property-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.location {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 1.1rem;
}

.rating {
  display: flex;
  align-items: center;
  gap: 10px;
}

.review-count {
  color: #666;
  font-size: 0.9rem;
}

.property-description,
.property-amenities,
.property-rules,
.property-reviews {
  margin-bottom: 40px;
}

.property-description h3,
.property-amenities h3,
.property-rules h3,
.property-reviews h3 {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 20px;
}

.property-description p {
  line-height: 1.8;
  color: #666;
  font-size: 1.1rem;
}

.amenities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.amenity-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.amenity-item .el-icon {
  font-size: 20px;
  color: #409eff;
}

.rules-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.rule-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rule-item h4 {
  color: #333;
  margin-bottom: 10px;
  font-size: 1.1rem;
}

.rule-item p {
  color: #666;
  margin: 0;
}

.reviews-summary {
  margin-bottom: 30px;
}

.rating-breakdown {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rating-item span:first-child {
  min-width: 60px;
  color: #666;
}

.rating-item span:last-child {
  min-width: 40px;
  text-align: right;
  color: #666;
  font-size: 0.9rem;
}

.reviews-list {
  space-y: 20px;
}

.review-item {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.reviewer-details h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.reviewer-details p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.review-content p {
  line-height: 1.6;
  color: #333;
  margin-bottom: 15px;
}

.review-ratings {
  display: flex;
  gap: 20px;
  margin-top: 15px;
  flex-wrap: wrap;
}

.rating-tag {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  color: #666;
}

.no-reviews {
  padding: 40px 0;
  text-align: center;
}

.review-actions {
  display: flex;
  gap: 20px;
}

.booking-sidebar {
  position: sticky;
  top: 20px;
}

.booking-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 20px;
}

.price-section {
  margin-bottom: 30px;
}

.price {
  display: flex;
  align-items: baseline;
  gap: 5px;
  margin-bottom: 20px;
}

.amount {
  font-size: 2rem;
  font-weight: bold;
  color: #ff4757;
}

.unit {
  color: #666;
  font-size: 1.1rem;
}

.price-details {
  space-y: 10px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.price-item.total {
  font-weight: bold;
  color: #333;
  font-size: 1.1rem;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.booking-btn {
  width: 100%;
  height: 50px;
  font-size: 1.1rem;
}

/* 点赞按钮样式 */
.review-actions .like-icon {
  font-size: 20px;
  margin-right: 5px;
  display: inline-block;
  transition: all 0.3s ease;
  filter: grayscale(100%);
}

.review-actions .like-icon.active {
  filter: grayscale(0%);
  transform: scale(1.2);
  animation: likeAnimation 0.3s ease;
}

.review-actions .is-liked {
  color: #409eff;
}

@keyframes likeAnimation {
  0% { transform: scale(1); }
  50% { transform: scale(1.3); }
  100% { transform: scale(1.2); }
}

/* 商家回复样式 */
.host-reply {
  margin-top: 20px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-left: 3px solid #409eff;
  border-radius: 8px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #666;
  font-size: 0.9rem;
}

.reply-icon {
  color: #409eff;
  font-size: 16px;
}

.reply-label {
  font-weight: 600;
  color: #409eff;
}

.reply-date {
  color: #999;
  font-size: 0.85rem;
}

.reply-content {
  color: #333;
  line-height: 1.6;
  font-size: 0.95rem;
}

@media (max-width: 768px) {
  .detail-content {
    grid-template-columns: 1fr;
  }
  
  .property-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .property-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .amenities-grid,
  .rules-grid,
  .rating-breakdown {
    grid-template-columns: 1fr;
  }
  
  .booking-sidebar {
    position: static;
  }
}
</style>


